package fr.obsmip.sedoo.client.ui;

import org.gwtbootstrap3.client.ui.Alert;
import org.gwtbootstrap3.client.ui.constants.AlertType;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import fr.sedoo.commons.client.widget.button.ImagedButton;


public class LoginViewImpl extends AbstractSection implements LoginView {
	
	Presenter presenter;
	
	@UiField
	TextBox login;
	
	@UiField
	PasswordTextBox password;
	
	@UiField 
	Button connectButton;
	
	@UiField 
	ImagedButton googleConnectButton;
	
	@UiField 
	ImagedButton facebookConnectButton;
	
	@UiField
	Alert okMessagePanel;
	
	@UiField
	Alert koMessagePanel;
	
	@UiField
	Alert loginFirst;
	
	private static LoginViewImplUiBinder uiBinder = GWT
			.create(LoginViewImplUiBinder.class);

	interface LoginViewImplUiBinder extends UiBinder<Widget, LoginViewImpl> {
	}

	public LoginViewImpl() {
		super();
//		loginFirst.setType(AlertType.DANGER);
		initWidget(uiBinder.createAndBindUi(this));
		applyCommonStyle();
		facebookConnectButton.setVisible(false);
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
		
	}
	
	 @UiHandler("connectButton")
	  void onSignInClicked(ClickEvent event) {
		 setConnectionEnabled(false);
		  presenter.login(login.getText(), password.getText());
	  }
	 
	 private void setConnectionEnabled(boolean value) 
	 {
		 connectButton.setEnabled(value);
		 googleConnectButton.setEnabled(value);
	}

	@UiHandler("googleConnectButton")
	  void onGoogleSignInClicked(ClickEvent event) {
		setConnectionEnabled(false);
		presenter.loginWithGoogle();
	  }
	 
	 @UiHandler("facebookConnectButton")
	  void onFacebookSignInClicked(ClickEvent event) {
		presenter.loginWithFacebook();
	  }
	 
	@Override
	public void updateSucces() {
		okMessagePanel.setVisible(true);
		koMessagePanel.setVisible(false);
		loginFirst.setVisible(false);
		
	}

	@Override
	public void updateFailure() {
		okMessagePanel.setVisible(false);
		koMessagePanel.setVisible(true);
		setConnectionEnabled(true);
	}
	
	@Override
	public void reset()
	{
		password.setText("");
		login.setText("");
		okMessagePanel.setVisible(false);
		koMessagePanel.setVisible(false);
		setConnectionEnabled(true);
	}

	@Override
	public void setLoginFirstMessageVisible(boolean value) 
	{
		loginFirst.setVisible(value);
	}

	@Override
	public void activateLoginButtons() {
		setConnectionEnabled(true);
	}

}
